<?php
// 获取请求参数
$action = $_GET['action'];

header('Content-Type: application/json');
$table_ad = C::t('#erling_gridad_image#ad_image');
$table_configs = C::t('#erling_gridad_image#configs_image');

if($action == 'add'|| $action == 'edit' || $action == 'renew') {
    // 获取请求参数
    $form_data = $_POST['data'];

    // 参数校验
    if(empty($form_data['time_select']) || 
       !isset($form_data['time_select']['type']) || 
       !isset($form_data['time_select']['num']) ||
       !in_array($form_data['time_select']['type'], ['daily_credit', 'monthly_credit']) ||
       !ctype_digit((string)$form_data['time_select']['num']) || 
       $form_data['time_select']['num'] <= 0) {
        $data = [
            'success' => false,
            'message' => '时间选择参数无效，请检查类型和数量',  
        ];
        echo json_encode($data);
        exit;
    }

}
// 如果是删除或编辑，需判断uid是否一致
if($action == 'delete' || $action == 'edit') {
    $id = intval($_GET['ad_id']); // 获取广告ID
    $ad_info = $table_ad->fetch($id); // 获取广告信息

    if(!$ad_info) {
        $data = [
           'success' => false,
           'message' => '广告不存在'
        ];
        echo json_encode($data);
        exit;
    } elseif($ad_info['uid'] != $_G['uid']) {
        $data = [
          'success' => false,
          'message' => '权限不足'
        ];
        echo json_encode($data);
        exit;
    }
}

if ($action == 'add') {
    // 处理数据
    $enable_audit = $table_configs->fetch_by_key('enable_audit')['value'];
    $save_data = [
        'uid' => $_G['uid'],
        'title' => $form_data['title'],
        'image' => $form_data['image'],
        'url' => $form_data['url'], 
        'bgcolor' => $form_data['bgcolor'],
        'color' => $form_data['color'],
        'bold' => $form_data['underline'] == 'true' ? 1 : 0,
        'underline' => $form_data['underline'] == 'true' ? 1 : 0,
        'italic' => $form_data['italic'] == 'true' ? 1 : 0,
        'position' => $form_data['position'],
        'type' => 'grid',
        'sort' => $form_data['sort'],
        'status' => $enable_audit=='1' ? 3 : 1,
    ];
    // 获取配置中的 daily_credit 和 monthly_credit 值
    $credit_config = $table_configs->fetch_by_keys(['daily_credit', 'monthly_credit', 'credit_type']);
    $daily_credit = $credit_config['daily_credit']['value'];
    $monthly_credit = $credit_config['monthly_credit']['value'];
    $time_select = $form_data['time_select'];
    
    // 计算过期时间和租金
    if($time_select['type'] == 'daily_credit') {
        $expire_time = time() + ($time_select['num'] * 86400);
        $rent_credit = $time_select['num'] * $daily_credit; 
    } elseif($time_select['type'] == 'monthly_credit') {
        $expire_time = strtotime("+{$time_select['num']} months");
        $rent_credit = $time_select['num'] * $monthly_credit;
    }
    
    // 将计算结果保存到save_data中
    $save_data['expire_time'] = $expire_time;
    $save_data['rent_credit'] = $rent_credit;

    $existing_ad = $table_ad->fetch_by_sort_status($save_data['sort'], [1, 3]);
    if($existing_ad) {
        $data = [
            'success' => false,
            'message' => '该位置已有广告存在，无法添加新广告，可刷新页面查看'
        ];
        echo json_encode($data);
        exit;
    }

    // 获取积分配置
    $credit_type = '2';
    if(!empty($credit_config['credit_type']['value'])) {
        $credit_type = $credit_config['credit_type']['value'];    
    }
    $extcredits = 'extcredits'.$credit_type;  

    // 检查积分
    $rent_credit = $save_data['rent_credit'];
    $user_credit = getuserprofile($extcredits);
    if ($user_credit < $rent_credit) {
        // 获取积分类型名称
        $extcredits_data = DB::fetch_first("SELECT svalue FROM %t WHERE skey = %s", array('common_setting', 'extcredits'));
        $extcredits_info = unserialize($extcredits_data['svalue']);
        $credit_name = $extcredits_info[$credit_type]['title'] ?? '';
        $data = [
            'success' => false,
            'message' => '您的 '.$credit_name.'积分 不足，无法添加广告',
        ];
        echo json_encode($data);
        exit;
    }

    $insert_id = $table_ad->insert($save_data);
    if(!$insert_id) {
        $data = [
            'success' => false,
            'message' => '数据插入失败'
        ];
        echo json_encode($data);
        exit;
    } else {
        // 更新用户积分
            $log_detail = "扣除广告位租金，标题：{$save_data['title']}";
            updatemembercount(
                $_G['uid'], 
                array($extcredits => -$rent_credit), 
                true, 
                'AD', 
                $insert_id,
                '',
                $log_detail
            );
    }
    $data = [
        'success' => true,
        'message' => $enable_audit=='1' ? '提交成功，请联系管理尽快通过审核' : '添加成功',
        'data' => $save_data
    ];
} elseif ($action == 'edit') {
    $ad_id = intval($_GET['ad_id']);
    $enable_audit = $table_configs->fetch_by_key('enable_audit')['value'];
    $save_data = [
        'title' => $form_data['title'],
        'image' => $form_data['image'],
        'url' => $form_data['url'], 
        'bgcolor' => $form_data['bgcolor'],
        'color' => $form_data['color'],
        'bold' => $form_data['underline'],
        'underline' => $form_data['underline'],
        'italic' => $form_data['italic'],
    ];
    $ad_info = $table_ad->fetch($ad_id);
    if($ad_info['status'] == 1 && $enable_audit == 1) {
        $save_data['status'] = 4;
    }
    $result = $table_ad->update($ad_id, $save_data);
    if(!$result) {
        $data = [
           'success' => false,
           'message' => '更新失败'
        ]; 
    } else {
        $data = [
          'success' => true,
          'message' => '更新成功'
        ]; 
    }
} elseif ($action == 'renew') {
    $ad_id = intval($_GET['ad_id']);
    $ad_info = $table_ad->fetch($ad_id);

    // 获取$ad_info中的rent_credit和expire_time
    $rent_credit = $ad_info['rent_credit'];
    $expire_time = $ad_info['expire_time'];

    // 获取配置中的 daily_credit 和 monthly_credit 值
    $credit_config = $table_configs->fetch_by_keys(['daily_credit', 'monthly_credit', 'credit_type']);
    $daily_credit = $credit_config['daily_credit']['value'];
    $monthly_credit = $credit_config['monthly_credit']['value'];
    $time_select = $form_data['time_select'];
    
    // 计算过期时间和租金
    if($time_select['type'] == 'daily_credit') {
        $new_expire_time = $expire_time + ($time_select['num'] * 86400);
        $new_rent_credit = $time_select['num'] * $daily_credit;
    } elseif($time_select['type'] == 'monthly_credit') {
        $new_expire_time = strtotime("+{$time_select['num']} months", $expire_time);
        $new_rent_credit = $time_select['num'] * $monthly_credit;
    }

    // 获取积分配置
    $credit_type = '2';
    if(!empty($credit_config['credit_type']['value'])) {
        $credit_type = $credit_config['credit_type']['value'];    
    }
    $extcredits = 'extcredits'.$credit_type;  

    // 检查用户积分是否足够
    $user_credit = getuserprofile($extcredits);
    if ($user_credit < $new_rent_credit) {
        // 获取积分类型名称
        $extcredits_data = DB::fetch_first("SELECT svalue FROM %t WHERE skey = %s", array('common_setting', 'extcredits'));
        $extcredits_info = unserialize($extcredits_data['svalue']);
        $credit_name = $extcredits_info[$credit_type]['title'] ?? '';
        $data = [
            'success' => false,
            'message' => '您的 '.$credit_name.'积分 不足，无法续费',
        ];
        echo json_encode($data);
        exit;
    }

    $save_data = [
        'expire_time' => $new_expire_time,
        'rent_credit' => $rent_credit + $new_rent_credit, 
    ];
    $result = $table_ad->update($ad_id, $save_data);
    if(!$result) {
        $data = [
          'success' => false,
          'message' => '续期失败'
        ]; 
    } else {
        // 更新用户积分
        $log_detail = "扣除续费广告位租金，标题：{$ad_info['title']}";
        updatemembercount(
            $_G['uid'], 
            array($extcredits => -$new_rent_credit), 
            true, 
            'AD', 
            '',
            '',
            $log_detail
        );
        $data = [
            'success' => true,
            'message' => '续期成功'
        ];
    }
} elseif ($action == 'delete') {
        $result = $table_ad->delete($id);
        if(!$result) {
            $data = [
              'success' => false,
              'message' => '删除失败'
            ]; 
        } else {
            $data = [
               'success' => true,
               'message' => '删除成功' 
            ];
        }
} elseif ($action == 'get_ad') {
    $ad_id = intval($_GET['ad_id']);
    $ad_info = $table_ad->fetch($ad_id);
    if(!$ad_info) {
        $data = [
           'success' => false,
           'message' => '广告不存在'
        ]; 
    } else {
        $data = [
          'success' => true,
          'message' => '获取成功',
          'data' => $ad_info
        ];
    }
}

echo json_encode($data);